var dWelcome = document.querySelector('.welcome');
var dStartBtn = document.querySelector(".start-btn");
var dChoose_1 = document.querySelector(".choose-1");
var dDifficultyChoose = document.querySelector(".difficultyChoose");
var Introduction = document.querySelector(".Introduction");
var closeBtn0 = document.querySelector(".close_btn0");

var levelChoose = document.querySelector(".levelChoose")
var difficulty = document.querySelector(".difficulty")
var introduction = document.querySelector(".introduction")
var easyBtn = document.getElementById("easy");
var middleBtn = document.getElementById("middle");
var hardBtn = document.getElementById("hard");

var dContainer = document.querySelector('.container');
var dBall = document.querySelector('.ball');
var dBan = document.querySelector('.ban');
var dZhuan = document.getElementById('zhuan');

var fanhui1 = document.getElementById("fanhui1");
var fanhui2 = document.getElementById("fanhui2");
var fanhui3 = document.getElementById("fanhui3");
var fanhui4 = document.getElementById("fanhui4");
var fanhui5 = document.getElementById("fanhui5");

var timeDisplay = document.querySelector('#time-display');
var scoreDisplay = document.querySelector('#score-display');
var lifeDisplay = document.querySelector('#life-display');
var difDisplay = document.querySelector('#dif-display');

var winPopup = document.querySelector('#win-popup');
var losePopup = document.querySelector('#lose-popup');
var winScore = document.getElementById('win-score');
var winTime = document.getElementById('win-time');
var winGrade = document.getElementById('win-grade');
var finalScore = document.getElementById('final-score');
var finalTime = document.getElementById('final-time');
var finalGrade = document.getElementById('final-grade');
var closeBtns = document.querySelectorAll('.close-btn');
var returnLevelchooseBtns = document.querySelectorAll('.return-levelchoose-btn')
var restartBtns = document.querySelectorAll('.restart-btn')
var nextBtns = document.querySelectorAll('.next-btn')

var difLevel = 'easy';

var btn = document.querySelector('.btn');
var btn1 = document.querySelector('.btn1');
var btn2 = document.querySelector('.btn2');
var timer = null;
var isLeft = false; /* 判断板向左还是向右移动 */
var isRight = false;
var score = 0;
var scoreMax;
var dif; /* 游戏强度 */
var lifesInit;
var lifes; /* 生命值 */
var startTime; //开始时间
var interval; //计时器--记时间
var interval1; //记得分
var interval2; //记生命值

// 获取要添加按钮的父元素
var parent = document.getElementById("levelPerent");

// 创建一个表格元素
var levelTable = document.createElement("table");

var levelButs = document.querySelectorAll('.levelChoose .content2 .level');
var levelNum = 1;

//暂停 
var isPaused = false;

var juzhen = {
    juzhen1: [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    ],
    juzhen2: [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
        [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
        [1, 1, 0, 0, 0, 0, 0, 0, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 1]
    ],
    juzhen3: [
        [0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
        [0, 1, 1, 1, 0, 1, 1, 1, 1, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
        [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
        [0, 0, 0, 1, 1, 1, 1, 0, 0, 0]
    ],
    juzhen4: [
        [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
        [1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
        [1, 1, 0, 0, 0, 0, 0, 0, 1, 1],
        [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
        [1, 1, 1, 0, 0, 0, 1, 1, 0, 1],
        [1, 1, 0, 0, 1, 0, 0, 0, 0, 1]
    ],
    juzhen5: [
        [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
        [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
        [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
        [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
        [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
        [0, 0, 0, 0, 1, 1, 0, 0, 0, 0]
    ],
    juzhen6: [
        [0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
        [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
        [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
        [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
    ],
}

//设置难度
function changeBackground() {
    if (difLevel == "easy") {
        levelChoose.style.backgroundImage = "url('../img/levelChoose/easy_level_bg.jpg')";
    } else if (difLevel == "medium") {
        levelChoose.style.backgroundImage = "url('../img/levelChoose/medium_level_bg.jpg')";
    } else if (difLevel == "hard") {
        levelChoose.style.backgroundImage = "url('../img/levelChoose/hard_level_bg.jpg')";
    }
}

//添加砖
function setZhuan() {
    dZhuan.innerHTML = "";
    scoreMax = 0;
    var matrix = juzhen["juzhen" + levelNum];
    for (var i = 0; i < 6; i++) {
        for (var j = 0; j < 10; j++) {
            if (matrix[i][j] === 1) {
                var d = document.createElement("div");
                scoreMax++;
                d.className = "brick" + (Math.random() * 11 | 0);
            } else {
                var d = document.createElement("div");
                d.className = "brickNull" + (Math.random() * 11 | 0);
            }
            d.style.left = 25 + j * 56 + 'px';
            d.style.top = 30 + i * 15 + 'px';
            dZhuan.appendChild(d);
        }
    }
}

//设置小球
function setBall() {
    dBall.style.left = dBan.offsetLeft + (dBan.offsetWidth - dBall.offsetWidth) / 2 + 'px';
    dBall.style.top = dBan.offsetTop - dBall.offsetHeight + 'px';
    dBall.sx = Math.random() > 0.5 ? 7 : -1 * 7;
    dBall.sy = -1 * 7;
}
//清空小球
function clearBall() {
    dBall.style.left = '';
    dBall.style.top = 320;
    dBall.sx = 0;
    dBall.sy = 0;
}
//小球运动
function ballMove() {
    dBall.style.left = dBall.offsetLeft + dBall.sx * dif + 'px';
    dBall.style.top = dBall.offsetTop + dBall.sy * dif + 'px';
    dBall.style.backgroundColor = 'blue';
    if (dBall.offsetLeft <= 0 || dBall.offsetLeft >= 588) {
        dBall.sx *= -1;
    }
    if (dBall.offsetTop <= 12) {
        dBall.sy *= -1;
    }
    if (dBall.offsetTop >= 320) {
        if (lifes > 0) {

            lifes--;
            setBall();

        } else {
            lifes = 0;
            endGame(); /* 生命值结束,游戏结束 */
        }

    }
    if (score == scoreMax) { /* 砖块全部消除,游戏结束  */
        // score = score * lifes / score * lifesInit * 100;
        endGame();
    }
}

// 设置关卡表格
function setLevelBut() {

    // 创建两行三列的表格
    for (var i = 0; i < 2; i++) {
        // 创建一行
        var row = document.createElement("tr");
        for (var j = 0; j < 3; j++) {
            // 创建一个单元格
            var cell = document.createElement("td");
            // 创建一个按钮
            var levelBut = document.createElement("button");
            levelBut.className = 'level';
            levelBut.innerHTML = (i * 3 + j + 1);
            // 为按钮添加点击事件
            levelBut.addEventListener('click', function() {
                levelNum = this.parentNode.parentNode.rowIndex * 3 + this.parentNode.cellIndex + 1;
                // console.log(levelNum);
                // console.log(j);

                start();
            });
            // 将按钮添加到单元格中
            cell.appendChild(levelBut);
            // 将单元格添加到行中
            row.appendChild(cell);
        }
        // 将行添加到表格中
        levelTable.appendChild(row);
    }
    // 将表格添加到父元素中
    parent.appendChild(levelTable);
}
setLevelBut();


//挡板 状态
window.onkeydown = function(e) {
    if (e.keyCode === 37) {
        isLeft = true;
    }
    if (e.keyCode === 39) {
        isRight = true;
    }

}
window.onkeyup = function(e) {
    if (e.keyCode === 37) {
        isLeft = false;
    }
    if (e.keyCode === 39) {
        isRight = false;
    }
}

dContainer.onmousemove = function(e) {
    var left = e.clientX - dContainer.offsetLeft - dBan.offsetWidth / 2; // 获取鼠标相对于容器的横坐标
    left = left < 0 ? 0 : left;
    left = left > 540 ? 540 : left;
    dBan.style.left = left + 'px';
}

function banMove() {
    var left = dBan.offsetLeft;
    if (isLeft) {
        left -= 12
    }
    if (isRight) {
        left += 12
    }
    left = left < 0 ? 0 : left;
    left = left > 540 ? 540 : left;
    dBan.style.left = left + 'px';
}

//碰撞检测
function check() {
    //1. ban与ball
    if (isCrash(dBall, dBan)) {
        dBall.style.top = dBan.offsetTop - dBall.offsetHeight + 'px';
        dBall.sy *= -1;
    }
    //2.ball与砖
    var zs = dZhuan.children;
    for (var i = 0; i < zs.length; i++) {
        if (isCrash(zs[i], dBall)) {
            dBall.sy *= -1;
            // 删除砖
            dZhuan.removeChild(zs[i]);
            i--;
            score++;
            playCollisionSound(); //碰撞音效
        }
    }
}
// 开始按钮
dStartBtn.onclick = function(e) {
    var audio = document.getElementById("audio1");
    audio.play();
    choose_1();
    // start();
}

// 难度选择
difficulty.onclick = function(e) {
    difficultyChoose();
}

// 游戏介绍
introduction.onclick = function(e) {
    introductionUI();
}
closeBtn0.onclick=function(e){
    choose_1();
}

//简单
easyBtn.onclick = function(e) {
    dif = 0.8;
    lifesInit = 2;
    score = 0;
    // start(); /* 显示游戏初始界面 */
    difDisplay.innerHTML = '简单';
    difLevel = 'easy';
    changeBackground();
    levelChooseUI();
}

//中等难度
middleBtn.onclick = function(e) {
    dif = 1.4;
    lifesInit = 1;
    score = 0;
    // start();
    difDisplay.innerHTML = '中等';
    difLevel = 'medium';
    changeBackground();
    levelChooseUI();
}

//困难
hardBtn.onclick = function(e) {
    dif = 2;
    lifesInit = 0;
    score = 0;
    // start();
    difDisplay.innerHTML = '困难';
    difLevel = 'hard';
    changeBackground();
    levelChooseUI();
}

// 返回开始界面
fanhui1.onclick = function(e) {
    welcomeUI();
}


//返回choose-1
fanhui3.onclick = function() {
    choose_1();
}
fanhui4.onclick = function() {
    choose_1();
}

// 返回难度选择界面
fanhui5.onclick = function() {
    difficultyChoose();
}

btn.onclick = function() { /* 点击开始按钮,开始游戏 */
    start1();
}

btn1.onclick = function() { /* 点击暂停按钮,暂停游戏界面 */
    isPaused = true; //暂停按钮生效
    btn2.disabled = false; //继续键生效
}
btn2.onclick = function() { /* 点击继续按钮,游戏继续 */
    isPaused = false; //暂停键失效
}


fanhui2.onclick = function() {
    btn.disabled = false;
    // console.log("我点到了");
    losePopup.classList.add('hidden');
    winPopup.classList.add('hidden');
    // console.log("我点到了");
    endGame();
    levelChooseUI();

}

//开始游戏界面
function start() {
    lifes = lifesInit;
    score = 0;

    updateScore();
    updateLife();
    timeDisplay.innerHTML = 0 + 's';

    levelChoose.style.display = "none";
    dContainer.style.display = "block";
    setZhuan();
    setBall();

}
//游戏正式开始
function start1() {
    //开启计时器
    setBall();
    lifes = lifesInit;
    timer = setInterval(function() {
            if (isPaused === false) { /* 如果没有按下暂停键,游戏正常执行 */
                // 1.挡板运动
                banMove();
                // 2.小球运动
                ballMove();
                // 3.碰撞检测
                check();
            }
        }, 30)
        //禁止启动按钮,防止用户再点击
    btn.disabled = true;
    //生成计时器
    startTime = new Date().getTime();
    interval = window.setInterval(updateTime, 100);
    interval1 = window.setInterval(updateScore, 100);
    interval2 = window.setInterval(updateLife, 100);
}

function welcomeUI() {
    dWelcome.style.display = "flex";
    dChoose_1.style.display = "none";
    Introduction.style.display = "none";
    dDifficultyChoose.style.display = "none";
    levelChoose.style.display = "none";
    dContainer.style.display = "none";
}

function choose_1() {
    dWelcome.style.display = "none";
    dChoose_1.style.display = "flex";
    Introduction.style.display = "none";
    dDifficultyChoose.style.display = "none";
    levelChoose.style.display = "none";
    dContainer.style.display = "none";
}

function difficultyChoose() {
    dWelcome.style.display = "none";
    dChoose_1.style.display = "none";
    Introduction.style.display = "none";
    dDifficultyChoose.style.display = "flex";
    levelChoose.style.display = "none";
    dContainer.style.display = "none";
}

function introductionUI() {
    dWelcome.style.display = "none";
    dChoose_1.style.display = "none";
    Introduction.style.display = "flex";
    dDifficultyChoose.style.display = "none";
    levelChoose.style.display = "none";
    dContainer.style.display = "none";
}

function levelChooseUI() {
    dWelcome.style.display = "none";
    dChoose_1.style.display = "none";
    Introduction.style.display = "none";
    levelChoose.style.display = "flex";
    dDifficultyChoose.style.display = "none";
    dContainer.style.display = "none";
}

welcomeUI();
// start();

function updateTime() {
    //当前的时间减去之前的时间
    if (isPaused == false) {
        let time = new Date().getTime() - startTime;
        timeDisplay.innerHTML = Math.floor(time / 1000) + 's';
    }
}
//更新得分
function updateScore() {
    scoreDisplay.innerHTML = score + '块';
}
//更新生命值
function updateLife() {
    lifeDisplay.innerHTML = lifes + '次';
}

//游戏结束
function endGame() {
    /* 先检查游戏结束的类型,并弹出对应的结束页面 */
    checkGameResult();
    
    clearInterval(timer);
    dZhuan.innerHTML = "";
    // 设置得分
    scoreDisplay.innerHTML = score + '块';

    //显示最开始界面
    clearBall();
    score = 0;
    isPaused = false;
    start();

    let time = new Date().getTime() - startTime;
    btn.disabled = false;
    //清除interval这个计时器
    clear();

}

//随机函数
function rand(min, max) {
    return Math.round(Math.random() * (max - min) + min);
}

//清除计时器
function clear() {
    window.clearInterval(interval);
    window.clearInterval(interval1);
    window.clearInterval(interval2);
}
//碰撞检测
function isCrash(a, b) {
    var l1 = a.offsetLeft;
    var t1 = a.offsetTop;
    var r1 = l1 + a.offsetWidth;
    var b1 = t1 + a.offsetHeight;
    var l2 = b.offsetLeft;
    var t2 = b.offsetTop;
    var r2 = l2 + b.offsetWidth;
    var b2 = t2 + b.offsetHeight;
    if (r2 < l1 || r1 < l2 || b2 < t1 || b1 < t2) {
        return false;

    } else {
        return true;

    }
}

//游戏结束时判断结束原因
function checkGameResult() {
    if (lifes === 0 && score === scoreMax) {
        //显示成功界面
        showVictoryPopup();
    } else if (score === scoreMax) {
        //显示成功界面
        showVictoryPopup();
    } else if (lifes === 0) {
        showFailurePopup();
    }

}

//失败时弹出
function showFailurePopup() {
    let scoreFinal = ((score * (lifes + 1) - (lifesInit - lifes) * 10) / (scoreMax * (lifesInit + 1)) * 100).toFixed(2);
    if (scoreFinal < 0.0) {
        scoreFinal = 0;
    }
    finalScore.innerHTML = scoreFinal + '分';
    let time = new Date().getTime() - startTime;
    finalTime.innerHTML = Math.floor(time / 1000) + 's';
    //finalGrade.innerHTML = '优秀'
    if (scoreFinal === "100.00") {
        finalGrade.innerHTML = 'SSS';
    } else if (scoreFinal > 95.00) {
        finalGrade.innerHTML = 'SS';
    } else if (scoreFinal > 90.00) {
        finalGrade.innerHTML = 'A';
    } else if (scoreFinal > 80.00) {
        finalGrade.innerHTML = 'B';
    } else if (scoreFinal > 70.00) {
        finalGrade.innerHTML = 'C';
    } else if (scoreFinal > 50.00) {
        finalGrade.innerHTML = 'D';
    } else {
        finalGrade.innerHTML = 'F';
    }


    losePopup.classList.remove('hidden');
}

//成功时弹出
function showVictoryPopup() {
    let scoreFinal = ((score * (lifes + 1) - (lifesInit - lifes) * 10) / (scoreMax * (lifesInit + 1)) * 100).toFixed(2);

    winScore.innerHTML = scoreFinal + '分';
    let time = new Date().getTime() - startTime;
    winTime.innerHTML = Math.floor(time / 1000) + 's';
    //finalGrade.innerHTML = '优秀'
    if (scoreFinal === "100.00") {
        console.log('判断了SSS');
        winGrade.innerHTML = 'SSS';
    } else if (scoreFinal > 95.00) {
        console.log('判断了SS');
        winGrade.innerHTML = 'SS';
    } else if (scoreFinal > 90.00) {
        console.log('判断了A');
        winGrade.innerHTML = 'A';
    } else if (scoreFinal > 80.00) {
        console.log('判断了b');
        winGrade.innerHTML = 'B';
    } else if (scoreFinal > 70.00) {
        console.log('判断了c');
        winGrade.innerHTML = 'C';
    } else if (scoreFinal > 50.00) {
        console.log('判断了d');
        winGrade.innerHTML = 'D';
    } else {
        console.log('判断了f');
        winGrade.innerHTML = 'F';
    }

    winPopup.classList.remove('hidden'); /* 移除该类,显示元素 */
}

//关闭弹窗
closeBtns.forEach(function(btn) {
    btn.addEventListener('click', function() {
        console.log('点到我了');
        losePopup.classList.add('hidden');
        winPopup.classList.add('hidden');
    });
});

//返回关卡选择界面
returnLevelchooseBtns.forEach(function(btn) {
    btn.addEventListener('click', function() {
        losePopup.classList.add('hidden');
        winPopup.classList.add('hidden');
        levelChooseUI();
    })
})

//重新开始
restartBtns.forEach(function(btn) {
    btn.addEventListener('click', function() {
        losePopup.classList.add('hidden');
        winPopup.classList.add('hidden');
        start();
    })
})

//下一关
nextBtns.forEach(function(btn) {
    btn.addEventListener('click', function() {
        levelNum++;
        losePopup.classList.add('hidden');
        winPopup.classList.add('hidden');
        /* 判断:如果超出所设关卡数,则返回关卡选择界面 */
        if (levelNum <= 6) {
            start();
        } else {
            levelChooseUI();
        }
    })
})

function playCollisionSound() {
    // 在这里添加播放音效的逻辑
    var audio = new Audio('./audio/boom.mp3');
    audio.play();
}